package org.lwxyz.utils.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yuwei
 * @version 1.0-SNAPSHOT
 * @description 操作redis工具类
 * @date 2018/1/29
 */
public class JedisUtil {
    private JedisUtil() {
    }

    private static class RedisUtilHolder {
        private static final JedisUtil instance = new JedisUtil();
    }

    /**
     * 获取JedisUtil对象
     * @return
     */
    public static JedisUtil getInstance() {
        return RedisUtilHolder.instance;
    }

    private static Map<String, JedisPool> maps = new HashMap<String, JedisPool>();

    /**
     * 获取redis连接池
     * @param ip
     * @param port
     * @return
     */
    private static JedisPool getPool(String ip, int port) {
        String key = ip + ":" + port;
        JedisPool pool = null;
        if (!maps.containsKey(key)) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(RedisConfig.MAX_ACTIVE);
            config.setMaxIdle(RedisConfig.MAX_IDLE);
            config.setMaxWaitMillis(RedisConfig.MAX_WAIT);
            config.setTestOnBorrow(true);
            config.setTestOnReturn(true);

            pool = new JedisPool(config, ip, port, RedisConfig.TIMEOUT);
            maps.put(key, pool);
        } else {
            pool = maps.get(key);
        }
        return pool;
    }

    /**
     * 获取redis连接
     * @param ip
     * @param port
     * @return
     */
    public Jedis getJedis(String ip, int port) {
        Jedis jedis = null;
        int count = 0;
        do {
            try {
                jedis = getPool(ip, port).getResource();
            } catch (Exception e) {
                e.printStackTrace();
                getPool(ip, port).returnBrokenResource(jedis);
            }
        }
        while (jedis == null && count < RedisConfig.RETRY_NUM);
        return jedis;
    }

    /**
     * 关闭redis连接
     * @param jedis
     * @param ip
     * @param port
     */
    public void closeJedis(Jedis jedis, String ip, int port) {
        if (jedis != null) {
            getPool(ip, port).returnResource(jedis);
        }
    }

    /**
     * 获取默认的jedis（服务器：localhost，端口：6379）
     * @return
     */
    public static Jedis getDefaultJedis(){
        return JedisUtil.getInstance().getJedis(RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT);
    }
}
